package com.my.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.my.controller.AdminController;
import com.my.domain.Result;
import com.my.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class AdminInterceptor implements HandlerInterceptor {//管理员权限拦截器

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute(AdminController.LOGIN_USER);
        if (loginUser == null || loginUser.getStatus() == null || loginUser.getStatus() != 1) {
            response.setContentType("application/json;charset=UTF-8");
            objectMapper.writeValue(response.getWriter(), Result.newErrResult("您没有管理员权限！"));
            return false;
        }
        return true;
    }
}
